﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace RESP_IIWaterAssessment
{
    public partial class FinancePlanForm : Form
    {
        public FinancePlanForm()
        {
            InitializeComponent();
        }

        int regID, avpID;
        tb_financeplan financePlan;
        const string catFactLossType = "FactLossType";

        private void FinancePlanForm_Load(object sender, EventArgs e)
        {
            cbRegion.SelectedIndexChanged -= cbRegion_SelectedIndexChanged;
            cbRegion.DataSource = UtilClass.FillCBRegions();
            cbRegion.DisplayMember = "Name";
            cbRegion.ValueMember = "ID";

            if (InformationClass.isAdmin)
            {
                cbRegion.SelectedIndex = -1;
                cbRegion.Text = string.Empty;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
            }
            else
            {
                cbRegion.Enabled = false;
                regID = InformationClass.regionID;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
                cbRegion.SelectedValue = regID;
                cbRegion_SelectedIndexChanged(cbRegion, null);
                cbAVP.Enabled = true;
                cbAVP.Text = string.Empty;
                //toolStrip1.Visible = false;
            }

            string[] month;
            if (InformationClass.Lang)
                month = new string[] { "Январь", "Февраль", "Март", "Апрель", "Май", "Июнь", "Июль", "Август", "Сентябрь", "Октябрь", "Ноябрь", "Декабрь" };
            else
                month = new string[] { "Январ", "Феврал", "Март", "Апрел", "Май", "Июн", "Июл", "Август", "Сентябр", "Октябр", "Ноябр", "Декабр" };

            for (int i = 1; i <= 12; i++)
            {
                var m = new
                {
                    ID = i,
                    Name = month[i - 1]
                };
                cbMonth.Items.Add(m);
            }
            cbMonth.DisplayMember = "Name";
            cbMonth.ValueMember = "ID";

            for (int i = 1991; i < 2100; i++)
            {
                cbYear.Items.Add(i);
            }
            cbMonth.SelectedIndex = cbMonth.FindStringExact(month[DateTime.Now.Month - 1]);
            cbYear.SelectedIndex = cbYear.FindStringExact(DateTime.Now.Year.ToString());

            cbFactLossType.SelectedIndexChanged -= cbFactLossType_SelectedIndexChanged;

            cbFactLossType.DataSource = UtilClass.FillCBCategory(catFactLossType);

            cbFactLossType.DisplayMember = "Name";
            cbFactLossType.ValueMember = "ID";
            cbFactLossType.SelectedIndex = -1;
            cbFactLossType.Text = string.Empty;
            cbFactLossType.SelectedIndexChanged += new EventHandler(cbFactLossType_SelectedIndexChanged);
        }

        private void cbRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbRegion.SelectedIndex >= 0)
            {
                cbAVP.Enabled = true;
                regID = Convert.ToInt32(cbRegion.SelectedValue);
                cbAVP.SelectedIndexChanged -= cbAVP_SelectedIndexChanged;
                cbAVP.DataSource = UtilClass.FillAVP(regID);
                cbAVP.ValueMember = "ID";
                cbAVP.DisplayMember = "Name";
                cbAVP.SelectedIndex = -1;
                cbAVP.Text = string.Empty;
                cbAVP.SelectedIndexChanged += new EventHandler(cbAVP_SelectedIndexChanged);
            }
        }

        private void cbAVP_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbAVP.SelectedIndex >= 0)
            {
                avpID = Convert.ToInt32(cbAVP.SelectedValue);
                int m = cbMonth.SelectedIndex + 1;
                int y = Convert.ToInt32(cbYear.Text);
                ShowState(avpID, m, y);
                //avpIncome = DBClass.AVPIncomes.Where(wh => wh.AVPID == avpID && )
            }
        }

        private void ShowState(int avpID, int month, int year)
        {
            if (avpID > 0)
            {
                var plan = DBClass.Financepians
                    .Where(wh => wh.AVPID == avpID && wh.Date == new DateTime(year, month, 1))
                    .Select(se => new
                    {
                        AverageCost = se.AverageCost,
                        FactLoss = se.FactLossType,
                        LossAmount = se.LossAmount
                    }).ToList();
                dgvFactLoss.DataSource = plan;

                dgvFactLoss.Columns["AverageCost"].Visible = false;
                if (InformationClass.Lang)
                {
                    dgvFactLoss.Columns["FactLoss"].HeaderText = "Вид Поступлений";
                    dgvFactLoss.Columns["LossAmount"].HeaderText = "Количество (тыс.сум)";
                }
                else
                {
                    dgvFactLoss.Columns["FactLoss"].HeaderText = "Киримлар тури";
                    dgvFactLoss.Columns["LossAmount"].HeaderText = "Қиймати (минг сўм)";
                }

                if (plan != null)
                {
                    if (dgvFactLoss.RowCount > 0)
                    {
                        tbAverageCost.Text = (dgvFactLoss["AverageCost", 0].Value != null) ? dgvFactLoss["AverageCost", 0].Value.ToString() : string.Empty;
                    }
                }
            }
        }

        private void buttonAverageCost_Click(object sender, EventArgs e)
        {
            if (avpID > 0)
            {
                decimal avCost;
                tbAverageCost.Text.GetDecimalOrDefault(out avCost);

                int m = cbMonth.SelectedIndex + 1;
                int y = Convert.ToInt32(cbYear.Text);

                var ACPlan = DBClass.Financepians
                    .Where(wh => wh.AVPID == avpID && wh.Date == new DateTime(y, m, 1));

                if (ACPlan != null)
                {
                    foreach (tb_financeplan item in ACPlan)
                    {
                        item.AverageCost = avCost;
                    }
                    try
                    {
                        DBClass.RESPContext.SubmitChanges();
                        MessageBox.Show(msgClass.msgSubmitChanges, msgClass.msgAchtung);
                    }
                    catch
                    {
                        MessageBox.Show(msgClass.msgError, msgClass.msgAchtung);
                    }
                }

            }
        }

        private void cbMonth_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (avpID > 0)
            {
                int m = cbMonth.SelectedIndex + 1;
                int y = Convert.ToInt32(cbYear.Text);
                ShowState(avpID, m, y);
            }
        }

        private void cbYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (avpID > 0)
            {
                int m = cbMonth.SelectedIndex + 1;
                int y = Convert.ToInt32(cbYear.Text);
                ShowState(avpID, m, y);
            }
        }

        private void cbFactLossType_SelectedIndexChanged(object sender, EventArgs e)
        {
            ShowLoss();
        }

        private void ShowLoss()
        {
            if (avpID > 0 && cbFactLossType.SelectedIndex >= 0)
            {
                int lossType = Convert.ToInt32(cbFactLossType.SelectedValue);

                int m = cbMonth.SelectedIndex + 1;
                int y = Convert.ToInt32(cbYear.Text);

                financePlan = DBClass.Financepians
                    .Where(wh => wh.AVPID == avpID && wh.Date == new DateTime(y, m, 1) && wh.FactLossType == lossType).SingleOrDefault();

                if (financePlan != null)
                {
                    tbAmaunt.Text = financePlan.LossAmount.ToString();
                }
                else
                {
                    tbAmaunt.Text = string.Empty;
                }
            }
        }

        private void buttonAddLoss_Click(object sender, EventArgs e)
        {
            if (avpID > 0 && cbFactLossType.SelectedIndex >= 0)
            {
                int lossType = Convert.ToInt32(cbFactLossType.SelectedValue);
                int m = cbMonth.SelectedIndex + 1;
                int y = Convert.ToInt32(cbYear.Text);

                decimal amount, avCoct;

                bool correct = tbAmaunt.Text.GetDecimalOrDefault(out amount);
                correct &= tbAverageCost.Text.GetDecimalOrDefault(out avCoct);
                if (!correct)
                {
                    string msg = InformationClass.Lang ? "Введены не корректные данные. Продолжить?" : "Маълумотлар нотўғри тўлдирилган. Давом эттирилсинми?";
                    string head = InformationClass.Lang ? "Внимание" : "Диққат";
                    if (MessageBox.Show(msg, head, MessageBoxButtons.YesNo) == DialogResult.No)
                        return;
                }

                financePlan = DBClass.Financepians
                    .Where(wh => wh.AVPID == avpID && wh.Date == new DateTime(y, m, 1) && wh.FactLossType == lossType).SingleOrDefault();


                if (financePlan != null)
                {
                    financePlan.LossAmount = amount;
                }
                else
                {
                    financePlan = new tb_financeplan
                    {
                        AverageCost = avCoct,
                        AVPID = avpID,
                        Date = new DateTime(y, m, 1),
                        FactLossType = lossType,
                        LossAmount = amount
                    };
                    DBClass.Financepians.InsertOnSubmit(financePlan);
                }
                try
                {
                    DBClass.RESPContext.SubmitChanges();
                    MessageBox.Show(msgClass.msgSubmitChanges, msgClass.msgAchtung);
                    ShowState(avpID, m, y);
                }
                catch
                {
                    MessageBox.Show(msgClass.msgError, msgClass.msgAchtung);
                }
                
            }
        }

        private void dgvFactLoss_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (dgvFactLoss.Columns.Contains("FactLoss"))
            {
                if (e.ColumnIndex.Equals(dgvFactLoss.Columns["FactLoss"].Index) && e.Value != null)
                {
                    string newVal = UtilClass.GetCategoryDisplayName((int)e.Value, catFactLossType);
                    if (String.IsNullOrEmpty(newVal))
                        e.Value = "no data";
                    else
                        e.Value = newVal;
                }
            }
        }

        private void buttonAbort_Click(object sender, EventArgs e)
        {
            ShowLoss();
        }

        private void buttonDebtCancel_Click(object sender, EventArgs e)
        {
            if (dgvFactLoss.RowCount > 0)
            {
                tbAverageCost.Text = (dgvFactLoss["AverageCost", 0].Value != null) ? dgvFactLoss["AverageCost", 0].Value.ToString() : string.Empty;
            }
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            DBClass.RESPContext.SubmitChanges();
            this.Close();
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Close();
        }


    }
}
